﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Authorize.Core.IdentityServer;
using Authorize.Core.Store;
using IdentityServer4.Models;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using Microsoft.Extensions.DependencyInjection;

namespace Authorize.Core.Extensions
{
    public static class IdentityServerClientBuilderExtensions
    {
        public static IIdentityServerBuilder AddClientSource(this IIdentityServerBuilder builder)
        {
            builder.AddClientStore<ClientStore>();

            var existingCors = builder.Services.LastOrDefault(x => x.ServiceType == typeof(ICorsPolicyService));
            if (existingCors != null &&
                existingCors.ImplementationType == typeof(DefaultCorsPolicyService) &&
                existingCors.Lifetime == ServiceLifetime.Transient)
            {
                // if our default is registered, then overwrite with the InMemoryCorsPolicyService
                // otherwise don't overwrite with the InMemoryCorsPolicyService, which uses the custom one registered by the host
                builder.Services.AddTransient<ICorsPolicyService, CorsPolicyService>();
            }

            return builder;
        }
    }
}
